<template>
  <div class="user-list">
    <!-- 搜索卡片 -->
    <a-card :bordered="false" class="search-card">
      <a-form layout="inline" :model="searchForm">
        <a-form-item label="账号">
          <a-input
            v-model:value="searchForm.accountName"
            placeholder="请输入账号"
            allowClear
          />
        </a-form-item>
        <a-form-item label="昵称">
          <a-input
            v-model:value="searchForm.nickName"
            placeholder="请输入昵称"
            allowClear
          />
        </a-form-item>
        <a-form-item label="邮箱">
          <a-input
            v-model:value="searchForm.email"
            placeholder="请输入邮箱"
            allowClear
          />
        </a-form-item>
        <a-form-item label="手机号">
          <a-input
            v-model:value="searchForm.phoneNumber"
            placeholder="请输入手机号"
            allowClear
          />
        </a-form-item>
        <a-form-item label="用户类型">
          <a-select
            v-model:value="searchForm.userType"
            placeholder="请选择"
            style="width: 120px"
            allowClear
          >
            <a-select-option :value="UserType.STUDENT">学生</a-select-option>
            <a-select-option :value="UserType.REPAIR_WORKER">维修工</a-select-option>
            <a-select-option :value="UserType.ADMIN">管理员</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button
              type="primary"
              :icon="h(SearchOutlined)"
              @click="fetchData"
            >
              搜索
            </a-button>
            <a-button :icon="h(ReloadOutlined)" @click="resetSearch">
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 数据表格 -->
    <a-card :bordered="false">
      <template #title>
        <span>用户列表</span>
        <a-tag color="blue" style="margin-left: 8px;">
          共 {{ pagination.total }} 条
        </a-tag>
      </template>

      <template #extra>
        <a-button
          type="primary"
          :icon="h(PlusOutlined)"
          @click="showCreateModal"
        >
          新增用户
        </a-button>
      </template>

      <a-table
        :columns="columns"
        :data-source="dataSource"
        :loading="loading"
        :pagination="pagination"
        :locale="{ emptyText: '暂无数据' }"
        @change="handleTableChange"
        :scroll="{ x: 1200, y: 800 }"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'userType'">
            <a-tag :color="getUserTypeColor(record.userType)">
              {{ getUserTypeText(record.userType) }}
            </a-tag>
          </template>

          <template v-if="column.key === 'createdAt'">
            {{ formatDate(record.createdAt) }}
          </template>

          <template v-if="column.key === 'action'">
            <a-space>
              <a-button
                type="link"
                size="small"
                @click="showEditModal(record)"
              >
                编辑
              </a-button>
              <a-button
                type="link"
                size="small"
                danger
                @click="handleDelete(record)"
              >
                删除
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 新增用户弹窗 -->
    <a-modal
      v-model:open="createModalVisible"
      title="新增用户"
      @ok="handleCreate"
      :confirm-loading="createLoading"
    >
      <a-form
        ref="createFormRef"
        :model="createForm"
        :rules="createRules"
        layout="vertical"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="账号" name="accountName" required>
              <a-input
                v-model:value="createForm.accountName"
                placeholder="请输入账号"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="昵称" name="nickName" required>
              <a-input
                v-model:value="createForm.nickName"
                placeholder="请输入昵称"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="密码" name="password" required>
              <a-input-password
                v-model:value="createForm.password"
                placeholder="请输入密码"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="确认密码" name="checkPassword" required>
              <a-input-password
                v-model:value="createForm.checkPassword"
                placeholder="请再次输入密码"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="邮箱" name="email" required>
              <a-input
                v-model:value="createForm.email"
                placeholder="请输入邮箱"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="手机号" name="phoneNumber" required>
              <a-input
                v-model:value="createForm.phoneNumber"
                placeholder="请输入手机号"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="用户类型" name="userType" required>
              <a-select
                v-model:value="createForm.userType"
                placeholder="请选择用户类型"
              >
                <a-select-option :value="UserType.STUDENT">学生</a-select-option>
                <a-select-option :value="UserType.REPAIR_WORKER">维修工</a-select-option>
                <a-select-option :value="UserType.ADMIN">管理员</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12" v-if="createForm.userType === UserType.STUDENT">
            <a-form-item label="宿舍地址" name="dormitoryName">
              <a-input
                v-model:value="createForm.dormitoryName"
                placeholder="请输入宿舍地址"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>

    <!-- 编辑用户弹窗 -->
    <a-modal
      v-model:open="editModalVisible"
      title="编辑用户"
      @ok="handleEdit"
      :confirm-loading="editLoading"
    >
      <a-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        layout="vertical"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="昵称" name="nickName" required>
              <a-input
                v-model:value="editForm.nickName"
                placeholder="请输入昵称"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="邮箱" name="email" required>
              <a-input
                v-model:value="editForm.email"
                placeholder="请输入邮箱"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="手机号" name="phoneNumber" required>
              <a-input
                v-model:value="editForm.phoneNumber"
                placeholder="请输入手机号"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="用户类型" name="userType" required>
              <a-select
                v-model:value="editForm.userType"
                placeholder="请选择用户类型"
              >
                <a-select-option :value="UserType.STUDENT">学生</a-select-option>
                <a-select-option :value="UserType.REPAIR_WORKER">维修工</a-select-option>
                <a-select-option :value="UserType.ADMIN">管理员</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16" v-if="editForm.userType === UserType.STUDENT">
          <a-col :span="24">
            <a-form-item label="宿舍地址" name="dormitoryName">
              <a-input
                v-model:value="editForm.dormitoryName"
                placeholder="请输入宿舍地址"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, h } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { useUserStore } from '@/stores/user'
import { useAppStore } from '@/stores/app'
import { getUserList, register, deleteUser, adminUpdateUser } from '@/api/user'
import { UserType } from '@/types'
import type { User, UserQueryRequest, UserRegisterRequest, UserAdminUpdateRequest, PageResponse, PaginationState } from '@/types'
import { createPaginationFromResponse, handlePaginationNavigation } from '@/utils/pagination'
import type { FormInstance } from 'ant-design-vue'
import type { Rule } from 'ant-design-vue/es/form'
import {
  SearchOutlined,
  ReloadOutlined,
  PlusOutlined
} from '@ant-design/icons-vue'

const userStore = useUserStore()
const appStore = useAppStore()

const loading = ref(false)
const dataSource = ref<User[]>([])

// 搜索表单
const searchForm = reactive<UserQueryRequest>({
  accountName: '',
  nickName: '',
  email: '',
  phoneNumber: '',
  userType: undefined,
  pageSize: 10,
  current: 1,
  lastId: 0
})

// 分页状态管理
const paginationState = ref<PaginationState>({
  current: 1,
  pageSize: 10,
  total: 0,
  pages: 0,
  hasNext: false,
  nextCursor: 0,
  previousPageCursors: []
})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number, range: [number, number]) =>
    `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
})

// 当前页面的起始lastId（用于记录分页历史）
const currentPageLastId = ref(0)

// 表格列配置
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80
  },
  {
    title: '账号',
    dataIndex: 'accountName',
    key: 'accountName',
    width: 120
  },
  {
    title: '昵称',
    dataIndex: 'nickName',
    key: 'nickName',
    width: 120
  },
  {
    title: '用户类型',
    dataIndex: 'userType',
    key: 'userType',
    width: 100
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    key: 'email',
    width: 200
  },
  {
    title: '手机号',
    dataIndex: 'phoneNumber',
    key: 'phoneNumber',
    width: 120
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    key: 'createdAt',
    width: 120
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    fixed: 'right' as const
  }
]

// 新增用户相关
const createModalVisible = ref(false)
const createLoading = ref(false)
const createFormRef = ref<FormInstance>()
const createForm = reactive<UserRegisterRequest>({
  accountName: '',
  nickName: '',
  password: '',
  checkPassword: '',
  email: '',
  phoneNumber: '',
  userType: UserType.STUDENT,
  dormitoryName: ''
})

// 编辑用户相关
const editModalVisible = ref(false)
const editLoading = ref(false)
const editFormRef = ref<FormInstance>()
const editForm = reactive<UserAdminUpdateRequest>({
  id: 0,
  nickName: '',
  email: '',
  phoneNumber: '',
  userType: UserType.STUDENT,
  dormitoryName: ''
})

// 新增用户表单验证规则
const createRules: Record<string, Rule[]> = {
  accountName: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 3, max: 20, message: '账号长度为3-20个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '账号只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  nickName: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '昵称长度为2-20个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度为6-20个字符', trigger: 'blur' },
    { pattern: /^(?=.*[a-zA-Z])(?=.*\d)/, message: '密码必须包含字母和数字', trigger: 'blur' }
  ],
  checkPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (_rule: Rule, value: string): Promise<void> => {
        if (value && value !== createForm.password) {
          return Promise.reject(new Error('两次输入的密码不一致'))
        }
        return Promise.resolve()
      },
      trigger: 'blur'
    }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phoneNumber: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  userType: [
    { required: true, message: '请选择用户类型', trigger: 'change' }
  ],
  dormitoryName: [
    { max: 100, message: '宿舍地址不能超过100个字符', trigger: 'blur' }
  ]
}

// 编辑用户表单验证规则
const editRules: Record<string, Rule[]> = {
  nickName: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '昵称长度为2-20个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phoneNumber: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  userType: [
    { required: true, message: '请选择用户类型', trigger: 'change' }
  ],
  dormitoryName: [
    { max: 100, message: '宿舍地址不能超过100个字符', trigger: 'blur' }
  ]
}

// 获取用户类型颜色
const getUserTypeColor = (type: UserType) => {
  const colorMap = {
    [UserType.STUDENT]: 'blue',
    [UserType.REPAIR_WORKER]: 'green',
    [UserType.ADMIN]: 'red'
  }
  return colorMap[type] || 'default'
}

// 获取用户类型文本
const getUserTypeText = (type: UserType) => {
  const textMap = {
    [UserType.STUDENT]: '学生',
    [UserType.REPAIR_WORKER]: '维修工',
    [UserType.ADMIN]: '管理员'
  }
  return textMap[type] || '未知'
}

// 格式化日期
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleDateString()
}

// 获取用户列表
const fetchData = async (resetPagination = false, useLastId?: number) => {
  try {
    loading.value = true

    if (resetPagination) {
      // 重置分页状态
      paginationState.value = {
        current: 1,
        pageSize: searchForm.pageSize || 10,
        total: 0,
        pages: 0,
        hasNext: false,
        nextCursor: 0,
        previousPageCursors: []
      }
      currentPageLastId.value = 0
    }

    const queryParams = { ...searchForm }
    queryParams.pageSize = paginationState.value.pageSize
    queryParams.current = paginationState.value.current
    queryParams.lastId = useLastId !== undefined ? useLastId : currentPageLastId.value

    const response = await getUserList(queryParams)
    if (response.code === 0 && response.data) {
      const pageData = response.data as PageResponse<User>

      // 更新数据源
      dataSource.value = pageData.records || []

      // 更新分页状态
      paginationState.value = {
        current: pageData.current,
        pageSize: pageData.size,
        total: pageData.total,
        pages: pageData.pages,
        hasNext: pageData.hasNext,
        nextCursor: pageData.nextCursor,
        previousPageCursors: paginationState.value.previousPageCursors
      }

      // 更新分页配置
      const paginationConfig = createPaginationFromResponse(pageData)
      Object.assign(pagination, paginationConfig)
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.accountName = ''
  searchForm.nickName = ''
  searchForm.email = ''
  searchForm.phoneNumber = ''
  searchForm.userType = undefined
  fetchData(true)
}

// 表格变化处理
const handleTableChange = (pag: any) => {
  const isNextPage = pag.current > paginationState.value.current
  const isPrevPage = pag.current < paginationState.value.current

  // 更新页面大小
  if (pag.pageSize !== paginationState.value.pageSize) {
    searchForm.pageSize = pag.pageSize
    paginationState.value.pageSize = pag.pageSize
    fetchData(true) // 页面大小变化时重置分页
    return
  }

  if (isNextPage && paginationState.value.hasNext) {
    // 向前翻页
    const navResult = handlePaginationNavigation(
      paginationState.value,
      'next',
      currentPageLastId.value
    )

    paginationState.value.current = navResult.current
    paginationState.value.previousPageCursors = navResult.previousCursors
    currentPageLastId.value = navResult.lastId

    fetchData(false, navResult.lastId)
  } else if (isPrevPage && paginationState.value.current > 1) {
    // 向后翻页
    const navResult = handlePaginationNavigation(
      paginationState.value,
      'prev',
      currentPageLastId.value
    )

    paginationState.value.current = navResult.current
    paginationState.value.previousPageCursors = navResult.previousCursors
    currentPageLastId.value = navResult.lastId

    fetchData(false, navResult.lastId)
  }
}

// 显示新增弹窗
const showCreateModal = () => {
  createFormRef.value?.resetFields()
  createForm.accountName = ''
  createForm.nickName = ''
  createForm.password = ''
  createForm.checkPassword = ''
  createForm.email = ''
  createForm.phoneNumber = ''
  createForm.userType = UserType.STUDENT
  createForm.dormitoryName = ''
  createModalVisible.value = true
}

// 显示编辑弹窗
const showEditModal = (record: User) => {
  editFormRef.value?.resetFields()
  editForm.id = record.id
  editForm.nickName = record.nickName
  editForm.email = record.email
  editForm.phoneNumber = record.phoneNumber
  editForm.userType = record.userType
  editForm.dormitoryName = record.dormitoryName || ''
  editModalVisible.value = true
}

// 新增用户
const handleCreate = async () => {
  try {
    await createFormRef.value?.validate()
    createLoading.value = true

    const response = await register(createForm)
    if (response.code === 0) {
      message.success(response.message || '用户创建成功')
      createModalVisible.value = false
      fetchData()
    } else {
      message.error(response.message || '创建用户失败')
    }
  } catch (error: any) {
    console.error('创建用户失败:', error)
    // 处理网络错误或其他异常
    if (error?.response?.data?.message) {
      message.error(error.response.data.message)
    } else if (error?.message) {
      message.error(error.message)
    } else {
      message.error('网络错误，请重试')
    }
  } finally {
    createLoading.value = false
  }
}

// 编辑用户
const handleEdit = async () => {
  try {
    await editFormRef.value?.validate()
    editLoading.value = true

    const response = await adminUpdateUser(editForm)
    if (response.code === 0) {
      message.success(response.message || '用户更新成功')
      editModalVisible.value = false
      fetchData()
    } else {
      message.error(response.message || '更新用户失败')
    }
  } catch (error: any) {
    console.error('更新用户失败:', error)
    // 处理网络错误或其他异常
    if (error?.response?.data?.message) {
      message.error(error.response.data.message)
    } else if (error?.message) {
      message.error(error.message)
    } else {
      message.error('网络错误，请重试')
    }
  } finally {
    editLoading.value = false
  }
}

// 删除用户
const handleDelete = (record: User) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除用户 "${record.accountName}" 吗？此操作不可恢复。`,
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      try {
        const response = await deleteUser({ id: record.id })
        if (response.code === 0) {
          message.success('删除成功')
          fetchData()
        }
      } catch (error) {
        console.error('删除用户失败:', error)
      }
    }
  })
}

onMounted(() => {
  // 检查权限
  if (!userStore.isAdmin) {
    message.error('没有权限访问此页面')
    return
  }

  // 设置面包屑
  appStore.setBreadcrumbs([
    { title: '首页', path: '/dashboard' },
    { title: '用户管理' },
    { title: '用户列表' }
  ])

  fetchData()
})
</script>

<style scoped>
.user-list {
  padding: 0;
}

.search-card {
  margin-bottom: 16px;
  padding-bottom: 20px;
}

.search-card .ant-form {
  gap: 16px;
}

.search-card :deep(.ant-card-body) {
  padding-bottom: 0;
}
</style>
